package com.cheer.ba.view.fragment;

import android.Manifest;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cheer.ba.R;
import com.cheer.ba.app.App;
import com.cheer.ba.app.oss.OssManager;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.H5Address;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.ArticleModel;
import com.cheer.ba.model.BannerModel;
import com.cheer.ba.model.CheerCircleModel;
import com.cheer.ba.model.CommentModel;
import com.cheer.ba.model.HotExchangeModel;
import com.cheer.ba.model.OilPriceModel;
import com.cheer.ba.model.PlayerModel;
import com.cheer.ba.model.PointModel;
import com.cheer.ba.presenter.impl.CommentPresenter;
import com.cheer.ba.presenter.impl.HomePresenter;
import com.cheer.ba.presenter.impl.PlayerPresenter;
import com.cheer.ba.service.LocationService;
import com.cheer.ba.utils.Currency;
import com.cheer.ba.utils.DensityUtils;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.Protect;
import com.cheer.ba.utils.ShareNewsUtil;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.SystemUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.activity.BaiduMapAty;
import com.cheer.ba.view.activity.CheerCircleAty;
import com.cheer.ba.view.activity.CheerCircleDetailAty;
import com.cheer.ba.view.activity.LookMyBillAty;
import com.cheer.ba.view.activity.CommH5RefreshAty;
import com.cheer.ba.view.activity.FindOilAty;
import com.cheer.ba.view.activity.FreePlayAty;
import com.cheer.ba.view.activity.MyOrderAty;
import com.cheer.ba.view.activity.MyPointAty;
import com.cheer.ba.view.activity.RequestFriendAty;
import com.cheer.ba.view.activity.TransitAty;
import com.cheer.ba.view.adapter.BannerPagerAdapter;
import com.cheer.ba.view.adapter.CheerCircleAdp;
import com.cheer.ba.view.adapter.HomeChannelAdp;
import com.cheer.ba.view.adapter.HomeChannelHolder;
import com.cheer.ba.view.adapter.HomeOilPriceAdp;
import com.cheer.ba.view.base.BaseCommFrg;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.ba.widget.MarqueeView;
import com.cheer.ba.widget.MyListView;
import com.cheer.ba.widget.ShowPopupView;
import com.cheer.ba.widget.banner.BannerIndicator;
import com.cheer.ba.widget.banner.LoopViewPager;
import com.cheer.ba.widget.headview.CheerHeadView;
import com.cheer.ba.widget.myrecycleview.BaseAdapter;
import com.cheer.ba.widget.myrecycleview.ScrollRecycler;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页刷新
 */
public class HomeFrg1 extends BaseCommFrg implements AdapterView.OnItemClickListener, ShowPopupView.OnItemPopupClick {

    @BindView(R.id.id_home_xrefresh_view)
    XRefreshView mXRefreshView;

    //************************ banner**********************/
    @BindView(R.id.id_layout_banner)
    FrameLayout mLayoutBanner;
    //轮播图
    @BindView(R.id.id_home_viewpager)
    LoopViewPager mViewpager;
    //轮播图上的点
    @BindView(R.id.id_home_indicator)
    BannerIndicator mIndicator;
    //轮播图适配器
    private BannerPagerAdapter mBannerAdp;
    //得到banner
    private List<BannerModel> mSaveBanners = new ArrayList<BannerModel>();

    //******************************今日油讯***************************/
    @BindView(R.id.id_today_article_layout)
    LinearLayout mLinearArticle;
    @BindView(R.id.id_today_news_txt)
    MarqueeView mTxtDayNews;
    //存储资讯
    private List<ArticleModel> mArticles = new ArrayList<ArticleModel>();

    //*****************************栏目*************************************/
    //栏目
    @BindView(R.id.id_home_recycler)
    ScrollRecycler mRecycler;
    private HomeChannelAdp mRecyclerAdp;
    private List<HotExchangeModel> mRecyclers = new ArrayList<HotExchangeModel>();

    //*************************油价*********************************************/
    //弹出框
    @BindView(R.id.id_show_oil_price_rela)
    RelativeLayout mRelaShowOil;
    @BindView(R.id.id_oil_price)
    TextView mTxtHomOilPrice;
    //今日油价
    @BindView(R.id.id_today_oil_price_linear)
    LinearLayout mLinearOilPrice;
    //油价
    @BindView(R.id.id_oil_price_recycler)
    ScrollRecycler mOilRecycler;
    private HomeOilPriceAdp mOilPriceAdp;
    private List<OilPriceModel> mOilRecyclers = new ArrayList<OilPriceModel>();

    //*****************************我的记录********************************************/
    //我的订单总额
    @BindView(R.id.id_order_num_txt)
    TextView mTxtTotalOrder;
    //我的积分总额
    @BindView(R.id.id_point_num_txt)
    TextView mTxtTotalPoint;

    //********************************热门活动*************************************************/
    //热门活动
    @BindView(R.id.id_hot_player_listv)
    MyListView mHotPlayListV;
    private CommonAdapter<PlayerModel> mHotPlayAdp;
    private List<PlayerModel> mHotPlays = new ArrayList<PlayerModel>();
    private PlayerPresenter mPlayerPresenter;

    //活动图片的高度
    private int activity_height;

    //*******************************加油圈******************************************************/
    //查看更多
    @BindView(R.id.id_load_rela)
    RelativeLayout mRelaLook;
    @BindView(R.id.id_circle_recyclev)
    RecyclerView mRecycleView;
    private CheerCircleAdp mCommentAdp;
    //存储柴油信息
    private List<CheerCircleModel> mCheerCircles = new ArrayList<CheerCircleModel>();
    //记录点赞的item下标
    private int mRecordLikePos;
    //记录点击的item
    private CheerCircleModel mRecordCircleItem;
    //记录删除评论或者回复的model
    private CommentModel mRecordCommentItem;
    //弹出头像框
    private ShowPopupView popupView;
    public static final String[] POPUP_ITEMS = {"删除"};
    public static final int[] POPUP_ITEMS_COLOR = {R.color.red};
    // 分享
    private ShareNewsUtil mShare;

    private CommentPresenter mCommentPresenter;

    //记录用户点击的导航还是上传经纬度 0 经纬度 1导航
    private int flag = 0;

    //定位服务
    private LocationService mLocationService;

    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.frg_home1, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new HomePresenter();

        mPlayerPresenter = new PlayerPresenter();
        mPlayerPresenter.attachView(this);

        mCommentPresenter = new CommentPresenter();
        mCommentPresenter.attachView(this);
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initView() {
        int width = SystemUtils.getScreenWidth(frg) - DensityUtils.dip2px(frg, 10);
        activity_height = (int) (202 * width / 710);
        //刷新
        setXRefreshView(mXRefreshView, true, false, false, false, new CheerHeadView(frg), null);

        //banner
        mLayoutBanner.getLayoutParams().height = DensityUtils.getScreenW(getActivity()) * 344 / 750;
        mLayoutBanner.requestLayout();
        //资讯
        mTxtDayNews.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
                if (!mArticles.isEmpty()) {
                    CommH5RefreshAty.startCommH5RefreshAty(frg, Protect.setPic(mArticles.get(position).articleUrl), "今日资讯");
                }
            }
        });
        //栏目
        LinearLayoutManager layoutManager = new LinearLayoutManager(frg);
        //设置布局管理器
        mRecycler.setLayoutManager(layoutManager);
        //设置为水平布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.HORIZONTAL);
//        mRecycler.addItemDecoration(new DividerItemDecoration(frg, DividerItemDecoration.HORIZONTAL_LIST));
        mRecyclerAdp = new HomeChannelAdp(mRecyclers, new OnRecyclerItemClick());
        //设置Adapter
        mRecycler.setAdapter(mRecyclerAdp);
        //设置增加或删除条目的动画
        mRecycler.setItemAnimator(new DefaultItemAnimator());
        //油价
        LinearLayoutManager oilPrice = new LinearLayoutManager(frg);
        mOilRecycler.setLayoutManager(oilPrice);
        oilPrice.setOrientation(OrientationHelper.HORIZONTAL);
        mOilPriceAdp = new HomeOilPriceAdp(mOilRecyclers, null);
        //设置Adapter
        mOilRecycler.setAdapter(mOilPriceAdp);
        //设置增加或删除条目的动画
        mOilRecycler.setItemAnimator(new DefaultItemAnimator());
        //热门活动
        mHotPlayAdp = new CommonAdapter<PlayerModel>(frg, mHotPlays, R.layout.adp_players) {
            @Override
            public void convert(ViewHolder helper, PlayerModel item) {
                if (null != item) {
                    ImageView img = (ImageView) helper.getViewById(R.id.id_players_img);
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, activity_height);
                    img.setLayoutParams(params);
                    helper.setRoundImageByUrl(R.id.id_players_img, Protect.setPic(item.getBackImg()), R.drawable.ic_error_show_bg, frg);
                    helper.setText(R.id.id_game_content_txt, item.getLotteryName());
                    //活动是否截至
                    ImageView mImgEnd = (ImageView) helper.getViewById(R.id.id_game_img);
                    mImgEnd.setVisibility(View.VISIBLE);
                    //当前日期
                    long currentTime = System.currentTimeMillis();
                    if (currentTime >= item.getStartDate() && currentTime < item.getEndDate()) {
                        mImgEnd.setVisibility(View.GONE);
                    } else if (currentTime < item.getStartDate()) {
                        //活动未开始
                        mImgEnd.setBackgroundResource(R.drawable.ic_play_no_begin);
                    } else {
                        //活动已结束
                        mImgEnd.setBackgroundResource(R.drawable.ic_game_over);
                    }
                }
            }
        };
        mHotPlayListV.setAdapter(mHotPlayAdp);
        mHotPlayListV.setOnItemClickListener(this);

        //加油圈
        popupView = new ShowPopupView(frg);
        popupView.setItemColor(POPUP_ITEMS_COLOR);
        popupView.setOnItemPopupClick(this);

        int cheerWidth = DensityUtils.getScreenW(frg);
        mRecycleView.setLayoutManager(new LinearLayoutManager(frg));
        mRecycleView.setHasFixedSize(true);
        mRecycleView.setNestedScrollingEnabled(false);

        mCommentAdp = new CheerCircleAdp(R.layout.adp_cheer_circle, mCheerCircles, cheerWidth);
//        mCommentAdp.openLoadAnimation(new CustomAnimation());
        mCommentAdp.setNotDoAnimationCount(3);
        mCommentAdp.isFirstOnly(false);
        mRecycleView.setAdapter(mCommentAdp);
        mCommentAdp.setOnSelfChildItemClick(new CheerCircleAdp.onSelfChildItemClick() {
            @Override
            public void onSelfItemClick(CheerCircleModel cheerCircleModel, CommentModel commentModel) {
                if (isLogin(true)) {
                    if (commentModel.delFlag == 0) {
                        mRecordCircleItem = cheerCircleModel;
                        mRecordCommentItem = commentModel;
                        if (TextUtils.equals(Session.getUserId(), commentModel.custId)) {
                            //自己的评论
                            popupView.showAtLocPop(mFrameRoot, POPUP_ITEMS);
                        } else {
                            //回复别人的评论
                            mCommentPresenter.showCommentPop(mFrameRoot, "2", "回复 " + commentModel.custNname + "：", true);
                        }
                    }
                }
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    public void OnItemClick(int position, String tag) {
        //删除评论或者回复
        mCommentPresenter.delMyComment(false, mRecordCommentItem.uid);
    }

    @Override
    public void initData() {
        if (Session.getUserIsLogin()) {
            //用户登录，上传经纬度
            flag = 0;
            checkOilPermiss();
        }
        List<BannerModel> mBannerList = ((HomePresenter) presenter).getCacheData();
        if (null != mBannerList && !mBannerList.isEmpty()) {
            updateViewWithTag(mBannerList, ConstantTag.HOME_BANNER);
            loadData();
        } else {
            mXRefreshView.startRefresh();
        }
        mXRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(final boolean isPullDown) {
                loadData();
            }
        });
        //获得首页标题-栏目
//        List<HotExchangeModel> recycles = (List<HotExchangeModel>) ((HomePresenter) presenter).getData(ConstantTag.HOME_TITLE);
//        mRecyclerAdp.fillList(recycles);
        //加油圈
        mCommentAdp.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CheerCircleModel model = (CheerCircleModel) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.id_jump_circle_detail_rela:
                        //进入详情
                        mRecordLikePos = position;
                        mRecordCircleItem = model;
                        Intent intent = new Intent(frg, CheerCircleDetailAty.class);
                        intent.putExtra(IntentKey.General.KEY_MODEL, model);
                        startActivity(intent);
                        break;
                    case R.id.id_circle_del_txt:
                        //删除
                        mRecordLikePos = position;
                        ((CommentPresenter) presenter).delDynamic(true, model.uid);
                        break;
                    case R.id.id_forward_rela:
                        //转发
                        String context = model.title.replaceAll("<br/>", "");
                        mShare = new ShareNewsUtil(frg, context, "加油省钱？选加油啦错不了！", H5Address.FORWARD_APP + model.webUrl + "?s=true", "");
                        mShare.showShare();
                        break;
                    case R.id.id_circle_like_linear:
                        //点赞
                        if (isLogin(true)) {
                            mRecordLikePos = position;
                            if (model.goodStatus == 1) {
                                //取消点赞
                                mCommentPresenter.userDelOperation(true, "4", "12", model.sourceId);
                            } else {
                                //点赞
                                mCommentPresenter.userOperation(true, "4", "12", model.sourceId);
                            }
                        }
                        break;
                    case R.id.id_circle_comment_txt:
                        //评论
                        if (isLogin(true)) {
                            mRecordCircleItem = model;
                            mCommentPresenter.showCommentPop(mFrameRoot, "1", "评论：", true);
                        }
                        break;
                }
            }
        });
    }

    /**
     * 加载数据
     */
    public void loadData() {
        //获取banner
        ((HomePresenter) presenter).getBanner();
        if (mArticles.isEmpty()) {
            //获取今日资讯
            ((HomePresenter) presenter).getTodayArticles(false, "1");
        }
        if (mOilRecyclers.isEmpty()) {
            //获取今日油价
            ((HomePresenter) presenter).getTodayOilPrice("湖北");
        }
        if (Session.getUserIsLogin()) {
            //获取我的消费总金额
            ((HomePresenter) presenter).getMyTotalOrder("", "");
            //获取我的总积分
            ((HomePresenter) presenter).getMyTotalPoint();
        } else {
            mTxtTotalOrder.setText("- -");
            mTxtTotalPoint.setText("- -");
        }
        if (mHotPlays.isEmpty()) {
            //获得热门活动
//            mPlayerPresenter.getPlayers(false);
        }
        //获得车友之家的动态
        mCommentPresenter.getDynamicList(false, false, 5);
        stopRefresh(mXRefreshView, 2000);
    }

    /**
     * 热门活动点击事件
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (isLogin(true)) {
            PlayerModel item = (PlayerModel) mHotPlayAdp.getItem(position);
            //当前日期
            long currentTime = System.currentTimeMillis();
            if (currentTime >= item.getStartDate() && currentTime < item.getEndDate()) {
                String url = H5Address.GET_PRIZE + "custId=" + Session.getUserId() + "&lottery_id=" + item.getUid();
                CommH5RefreshAty.startCommH5RefreshAty(frg, url, item.getLotteryName());
            } else if (currentTime < item.getStartDate()) {
                //活动未开始
                SVProgressHUD.showInfoWithStatus(frg, "该活动还未开始");
            } else {
                //活动已结束
                SVProgressHUD.showInfoWithStatus(frg, "该活动已结束");
            }
        }
    }

    /**
     * 栏目
     */
    public class OnRecyclerItemClick implements BaseAdapter.OnItemClickListener<HotExchangeModel, HomeChannelHolder> {
        @Override
        public void onItemClick(HomeChannelHolder holder, HotExchangeModel data) {
            int position = holder.getLayoutPosition();
            switch (position) {
                //车友圈
                case 0:
                    showActivity(frg, CheerCircleAty.class);
                    break;
                //优惠活动
                case 1:
                    showActivity(frg, FreePlayAty.class);
                    break;
                //油站导航
                case 2:
                    flag = 1;
                    checkOilPermiss();
//                    if (isLogin(true)) {
//                        EntityCache<BreakRulesModel> mSaveCarsCache = new EntityCache<BreakRulesModel>(frg, BreakRulesModel.class, IntentKey.BreakCar.BREAK_CACHE);
//                        List<BreakRulesModel> breaks = mSaveCarsCache.getListEntity(BreakRulesModel.class);
//                        if (null != breaks && !breaks.isEmpty()) {
//                            showActivity(frg, BreakRuleCarListAty.class);
//                        } else {
//                            showActivity(frg, BreakRulesCarAty.class);
//                        }
//                    }
                    break;
                //云记账
                case 3:
                    if (isLogin(true)) {
//                        if (Session.getUserBooks()) {
                        Intent intent = new Intent(frg, LookMyBillAty.class);
                        intent.putExtra(IntentKey.General.KEY_PAGE, IntentCode.General.JUMP_CLOUD);
                        showActivity(frg, intent);
//                        } else {
//                            Intent intent = new Intent(frg, AddMyCloudBooks.class);
//                            startActivityForResult(intent, IntentCode.Book.BOOK_REQUEST_CODE);
//                        }
                    }
                    break;
            }
        }
    }

    @OnClick({R.id.id_load_rela, R.id.id_oil_clear_img, R.id.id_diesel_oil_linear, R.id.id_ask_friend_rela, R.id.id_hom_cloud_rela, R.id.id_go_my_order_linear, R.id.id_go_my_point_linear, R.id.id_hot_player_txt, R.id.id_circle_rela})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_oil_clear_img:
                mRelaShowOil.setVisibility(View.GONE);
                break;
            case R.id.id_diesel_oil_linear:
                //柴油充值
                if (isLogin(true)) {
                    TransitAty.start2TransitAty(frg, IntentCode.General.JUMP_HOME_RECHARGE);
                }
                break;
            case R.id.id_ask_friend_rela:
                //邀请好友
                if (isLogin(true))
                    showActivity(frg, RequestFriendAty.class);
                break;
            case R.id.id_hom_cloud_rela:
                //云记账
                Intent intent = new Intent(frg, LookMyBillAty.class);
                intent.putExtra(IntentKey.General.KEY_PAGE, IntentCode.General.JUMP_CLOUD);
                showActivity(frg, intent);
                break;
            case R.id.id_send_oil_linear:
                //柴油配送
                showActivity(frg, FindOilAty.class);
                break;
            case R.id.id_go_my_order_linear:
                //查看我的订单
                if (isLogin(true)) {
//                    showActivity(frg, MyOilCardAty.class);
                    showActivity(frg, MyOrderAty.class);
                }
                break;
            case R.id.id_go_my_point_linear:
                //查看我的积分
                if (isLogin(true)) {
                    showActivity(frg, MyPointAty.class);
                }
                break;
            case R.id.id_hot_player_txt:
                //查看更多热门活动
                showActivity(frg, FreePlayAty.class);
                break;
            case R.id.id_load_rela:
            case R.id.id_circle_rela:
                //查看更多加油圈
                showActivity(frg, CheerCircleAty.class);
                break;
        }
    }

    /**
     * 处理banner显示
     */
    public void showBannerPager(List<BannerModel> mBanners) {
        mBannerAdp = new BannerPagerAdapter(mBanners, frg);
        mViewpager.setAdapter(mBannerAdp);
        mIndicator.setViewPager(mViewpager);
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        stopRefresh(mXRefreshView, 2000);
        if (null != t) {
            if (TextUtils.equals(ConstantTag.HOME_BANNER, tag)) {
                //首页banner
                List<BannerModel> mBanners = (List<BannerModel>) t;
                if (null != mBanners && !mBanners.isEmpty()) {
                    mLayoutBanner.setVisibility(View.VISIBLE);
                    mSaveBanners.clear();
                    mSaveBanners.addAll(mBanners);
//                if (mBanners.size() > 8) {
//                    mBanners = mBanners.subList(0, 7);
//                }
                    showBannerPager(mBanners);
                }
            } else if (TextUtils.equals(tag, ConstantTag.HOME_OIL)) {
                //获取今日油价
                List<HotExchangeModel> oils = (List<HotExchangeModel>) t;
                if (null != oils && !oils.isEmpty()) {
                    mRelaShowOil.setVisibility(View.VISIBLE);
                    HotExchangeModel model = oils.get(0);
                    String price = model.p0;
                    if (StringUtils.isEmpty(price)) {
                        mTxtHomOilPrice.setText("湖北 柴油 0# 今日油价：未知");
                    } else {
//                        TextViewUtils.setSpannableStyleColor(price + "元/升", price.length(), (price.length() + 3), mTxtHomOilPrice, R.color.color_333333);
                        mTxtHomOilPrice.setText("湖北 柴油 0# 今日油价：" + price + "元/升");
                    }
//                    mLinearOilPrice.setVisibility(View.VISIBLE);
//                    mOilRecyclers.clear();

//                    OilPriceModel oil1 = new OilPriceModel("柴油0#", model.p0);
//                    oil1.setRed(true);
//                    OilPriceModel oil2 = new OilPriceModel("汽油92#", model.p92);
//                    OilPriceModel oil3 = new OilPriceModel("汽油95#", model.p95);
//                    OilPriceModel oil4 = new OilPriceModel("汽油93#", model.p93);
//                    OilPriceModel oil5 = new OilPriceModel("汽油97#", model.p97);
//                    OilPriceModel oil6 = new OilPriceModel("汽油90#", model.p90);
//                    mOilRecyclers.add(oil1);
//                    mOilRecyclers.add(oil2);
//                    mOilRecyclers.add(oil3);
//                    mOilRecyclers.add(oil4);
//                    mOilRecyclers.add(oil5);
//                    mOilRecyclers.add(oil6);
////                    mOilPriceAdp.fillList(mOilRecyclers);
//                    mOilPriceAdp.notifyDataSetChanged();
                }
            } else if (TextUtils.equals(tag, ConstantTag.GET_ORDER_SUCCESS)) {
                //获取我的订单总额
                PointModel model = (PointModel) t;
                String money = Currency.returnDollar(model.money).replace("元", "");
                mTxtTotalOrder.setText(money);
            } else if (TextUtils.equals(tag, ConstantTag.GET_POINT_SUCCESS)) {
                //获取总积分成功
                PointModel model = (PointModel) t;
                mTxtTotalPoint.setText(Currency.returnDollar(Currency.RMB, model.score, 1).replace("积分", ""));
            } else if (TextUtils.equals(tag, ConstantTag.OIL_PLAYERS)) {
                //获取热门活动
                List<PlayerModel> plays = (List<PlayerModel>) t;
                if (null != plays && !plays.isEmpty()) {
                    mHotPlayListV.setVisibility(View.VISIBLE);
                    mHotPlays.clear();
                    mHotPlays.addAll(plays);
                    mHotPlayAdp.notifyDataSetChanged();
                }
            } else if (TextUtils.equals(tag, ConstantTag.LIKE_SUCCESS)) {
                //点赞成功
                for (int i = 0; i < mCheerCircles.size(); i++) {
                    if (i == mRecordLikePos) {
                        CheerCircleModel model = mCheerCircles.get(i);
                        model.goodStatus = 1;
                        model.goodCount += 1;
                        mCommentAdp.notifyDataSetChanged();
                        break;
                    }
                }
                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA_CIRCLE;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, ConstantTag.DEL_LIKE_SUCCESS)) {
                //取消点赞成功
                for (int i = 0; i < mCheerCircles.size(); i++) {
                    if (i == mRecordLikePos) {
                        CheerCircleModel model = mCheerCircles.get(i);
                        model.goodStatus = 0;
                        model.goodCount -= 1;
                        mCommentAdp.notifyDataSetChanged();
                        break;
                    }
                }
                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA_CIRCLE;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, "1")) {
                //评论
                String context = (String) t;
                mCommentPresenter.userComment(false, context, mRecordCircleItem.sourceType, mRecordCircleItem.sourceId, "");
            } else if (TextUtils.equals(tag, ConstantTag.COMMENT_SUCCESS)) {
                //评论成功
                ToastUtil.showToast("评论成功");
                CommentModel model = (CommentModel) t;
                if (null != model) {
                    if (null != mRecordCircleItem) {
                        model.custId = Session.getUserId();
                        model.custNname = Session.getUserName();
                        model.custImg = Session.getUserPicUrl().replace(OssManager.OSS_HOST, "");
                        List<CommentModel> mComments = mRecordCircleItem.getCommentList();
                        mComments.add(0, model);
                        mCommentAdp.notifyDataSetChanged();
                        mRecordCircleItem = null;
                    }
                } else {
                    mXRefreshView.startRefresh();
                }
                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA_CIRCLE;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, "2")) {
                //回复
                String context = (String) t;
                mCommentPresenter.userReply(false, context, mRecordCircleItem.sourceType, mRecordCircleItem.sourceId, mRecordCommentItem.custId, mRecordCommentItem.uid);
            } else if (TextUtils.equals(tag, ConstantTag.REPLY_SUCCESS)) {
                //回复成功
                ToastUtil.showToast("回复成功");
                CommentModel model = (CommentModel) t;
                if (null != model) {
                    if (null != mRecordCircleItem) {
                        model.custId = Session.getUserId();
                        model.custNname = Session.getUserName();
                        model.custImg = Session.getUserPicUrl().replace(OssManager.OSS_HOST, "");
                        model.replyCustNname = mRecordCommentItem.custNname;
                        model.replyCustImg = mRecordCommentItem.custImg;
                        model.replyCustId = mRecordCommentItem.custId;
                        List<CommentModel> mComments = mRecordCircleItem.commentList;
                        mComments.add(0, model);
                        mCommentAdp.notifyDataSetChanged();
                        mRecordCircleItem = null;
                    }
                }
                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA_CIRCLE;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(tag, ConstantTag.DEL_COMMENT_SUCCESS)) {
                ToastUtil.showToast("评论删除成功");
                //删除评论或者回复
                if (null != mRecordCircleItem) {
                    List<CommentModel> mComments = mRecordCircleItem.commentList;
                    for (CommentModel model : mComments) {
                        if (TextUtils.equals(model.uid, mRecordCommentItem.uid)) {
                            model.delFlag = 1;
                            mCommentAdp.notifyDataSetChanged();
                            break;
                        }
                    }
                    mRecordCircleItem = null;
                }
                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA_CIRCLE;
                EventBus.getDefault().post(del);
            } else if (TextUtils.equals(ConstantTag.DEL_DYNAMIC, tag)) {
                //动态删除
                if (mCheerCircles.size() == 1) {
                    mCheerCircles.clear();
                    mCommentAdp.notifyDataSetChanged();
                    dataStatus(3);
                } else {
                    mCheerCircles.remove(mRecordLikePos);
                    mCommentAdp.notifyDataSetChanged();
                }
                BaseEvent del = new BaseEvent();
                del.type = ConstantTag.REFRESH_DATA_CIRCLE;
                EventBus.getDefault().post(del);
            }
        }
    }

    @Override
    public <T> void updateViewWithLoadMore(T t, boolean loadMore, String tag) {
        stopRefresh(mXRefreshView, 2000);
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.GET_ARTICLE_LIST)) {
                //获取今日油讯
                List<ArticleModel> articles = (List<ArticleModel>) t;
                if (null != articles && !articles.isEmpty()) {
                    mLinearArticle.setVisibility(View.VISIBLE);

                    mArticles.clear();
                    mArticles.addAll(articles);
                    mTxtDayNews.startWithObjectList(mArticles);
                }
            } else if (TextUtils.equals(tag, ConstantTag.COMMENT_LIST_SUCCESS)) {
                mRecycleView.setVisibility(View.VISIBLE);
                mRelaLook.setVisibility(View.VISIBLE);

                if (!loadMore) {
                    mCheerCircles.clear();
                }
                //柴油批发信息
                List<CheerCircleModel> comments = (List<CheerCircleModel>) t;
                if (!comments.isEmpty()) {
                    if (!loadMore) {
                        mCommentAdp.clearSparse();
                    }
                    mCheerCircles.addAll(comments);
                    mCommentAdp.notifyDataSetChanged();
                } else {
                    if (loadMore) {
//                        mXRefreshView.setLoadComplete(true);
//                        ToastUtil.showToast(getString(R.string.no_more_data));
                    } else {
                        //没有数据
                        mRecycleView.setVisibility(View.GONE);
                        mRelaLook.setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        //返回类型
        String type = event.type;
        if (TextUtils.equals(type, IntentKey.General.KEY_CLICK)) {
            //点击首页
            if (null != mXRefreshView) {
                mXRefreshView.startRefresh();
            }
        } else if (TextUtils.equals(type, IntentKey.Login.KEY_LOGIN_SUCCESS)) {
            //登录成功
            mXRefreshView.startRefresh();
            flag = 0;
            checkOilPermiss();
//            //获取我的消费总金额
//            ((HomePresenter) presenter).getMyTotalOrder("", "");
//            //获取我的总积分
//            ((HomePresenter) presenter).getMyTotalPoint();
        } else if (TextUtils.equals(type, IntentKey.Login.KEY_APP_EXIT)) {
            //退出
            mTxtTotalOrder.setText("- -");
            mTxtTotalPoint.setText("- -");
        } else if (TextUtils.equals(type, IntentKey.Login.KEY_NOTICE_PAY)) {
            LogUtils.LogD(TAG, "支付成功-----------HomeFrg");
            //支付成功
            //获取我的消费总金额
            ((HomePresenter) presenter).getMyTotalOrder("", "");
        } else if (TextUtils.equals(type, IntentKey.Login.KEY_NOTICE_POINT)) {
            LogUtils.LogD(TAG, "积分变更-----------HomeFrg");
            //签到成功
            //获取我的总积分
            ((HomePresenter) presenter).getMyTotalPoint();
        } else if (TextUtils.equals(type, ConstantTag.PUBLISH_DYNAMIC)) {
            //发布成功
            mXRefreshView.startRefresh();
        } else if (TextUtils.equals(type, ConstantTag.DEL_DYNAMIC)) {
            //动态删除
//            if (mCheerCircles.size() == 1) {
//                mCheerCircles.clear();
//                mCommentAdp.notifyDataSetChanged();
//                dataStatus(3);
//            } else {
//                mCheerCircles.remove(mRecordLikePos);
//                mCommentAdp.notifyDataSetChanged();
//            }
        } else if (TextUtils.equals(type, ConstantTag.LIKE_SUCCESS)) {
            //点赞成功
//            for (int i = 0; i < mCheerCircles.size(); i++) {
//                if (i == mRecordLikePos) {
//                    CheerCircleModel model = mCheerCircles.get(i);
//                    model.goodStatus = 1;
//                    model.goodCount += 1;
//                    mCommentAdp.notifyDataSetChanged();
//                    break;
//                }
//            }
        } else if (TextUtils.equals(type, ConstantTag.DEL_LIKE_SUCCESS)) {
            //取消点赞成功
//            for (int i = 0; i < mCheerCircles.size(); i++) {
//                if (i == mRecordLikePos) {
//                    CheerCircleModel model = mCheerCircles.get(i);
//                    model.goodStatus = 0;
//                    model.goodCount -= 1;
//                    mCommentAdp.notifyDataSetChanged();
//                    break;
//                }
//            }
        } else if (TextUtils.equals(type, ConstantTag.COMMENT_SUCCESS)) {
            //评论成功
//            CommentModel model = (CommentModel) event.model;
//
//            List<CommentModel> mComments = mRecordCircleItem.getCommentList();
//            mComments.add(0, model);
//            mCommentAdp.notifyDataSetChanged();
//            mRecordCircleItem = null;
        } else if (TextUtils.equals(type, ConstantTag.REPLY_SUCCESS)) {
            //回复成功
//            CommentModel model = (CommentModel) event.model;
//
//            List<CommentModel> mComments = mRecordCircleItem.getCommentList();
//            mComments.add(0, model);
//            mCommentAdp.notifyDataSetChanged();
//            mRecordCircleItem = null;
        } else if (TextUtils.equals(type, ConstantTag.DEL_COMMENT_SUCCESS)) {
            //删除评论或者回复
//            CommentModel commentModel = (CommentModel) event.model;
//            List<CommentModel> mComments = mRecordCircleItem.getCommentList();
//            for (CommentModel model : mComments) {
//                if (TextUtils.equals(model.uid, commentModel.uid)) {
//                    model.delFlag = 1;
//                    mCommentAdp.notifyDataSetChanged();
//                    break;
//                }
//            }
//            mRecordCircleItem = null;
        } else if (TextUtils.equals(type, ConstantTag.REFRESH_DATA)) {
            //刷新数据
            mCommentPresenter.getDynamicList(false, false, 5);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 检测用户定位权限
     */
    private void checkOilPermiss() {
        String[] perms = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
        if (!mayRequestPermission(perms)) {
            return;
        }
        getBaiduLocation();
    }

    /**
     * 获取地址
     */
    public void getBaiduLocation() {
        if (flag == 1) {
            flag = 0;
            showActivity(frg, BaiduMapAty.class);
        } else {
            //上传经纬度
            getLocation();
        }
    }

    /**
     * 获取定位地址
     */
    public void getLocation() {
        mLocationService = ((App) frg.getApplication()).mLocationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        mLocationService.registerListener(mListener);
        mLocationService.setLocationOption(mLocationService.getDefaultLocationClientOption());
        //定位
        mLocationService.start();
    }

    /*****
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                if (null != location) {
                    Address mAddress = location.getAddress();
                    ((HomePresenter) presenter).uploadUserLocation(false, location.getLatitude() + "", location.getLongitude() + "", mAddress.province, mAddress.city, mAddress.district + mAddress.street, "1", "1", "1");
                }
            }
            mLocationService.stop();
        }

        public void onConnectHotSpotMessage(String s, int i) {
        }
    };

    @Override
    public void requestPermissionResult(boolean allowPermission) {
        if (allowPermission) {
            getBaiduLocation();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(frg).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onStop() {
        //注销监听
        if (null != mLocationService) {
            mLocationService.unregisterListener(mListener);
            //停止定位服务
            mLocationService.stop();
        }
        super.onStop();
    }
}
